<!-- ERP 样本的新增/修改 -->
<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="min-width: 800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <ContentWrap>
        <el-form-item prop="priceList" style="display: none" />
        <el-table :data="formData.priceList" :stripe="true">
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column label="价格" align="center" prop="price" min-width="160">
            <template #default="{ row }">
              <el-input
                v-model="row.price"
                placeholder="请输入价格"
                style="width: 140px"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column label="开始时间" align="center" prop="startTime" min-width="160">
            <template #default="{ row }">
              <el-date-picker v-model="row.startTime" placeholder="开始时间" class="!w-140px" />
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="center" prop="endTime" min-width="160">
            <template #default="{ row }">
              <el-date-picker v-model="row.endTime" placeholder="结束时间" class="!w-140px" />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" min-width="120px">
            <template #default="scope">
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.$index)"
                :disabled="formData.priceList.length <= 1"
              >
                删除此条
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
      <div style="text-align: center">
        <el-button @click="addPriceList">
          <Icon icon="ep:plus" class="mr-5px" />添加一行
        </el-button></div
      >
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/productPrice'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/erp/product/category'
import { ProductUnitApi, ProductUnitVO } from '@/api/erp/product/unit'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree, findPath } from '@/utils/tree'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

/** ERP 样本 表单 */
defineOptions({ name: 'ProductForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  barCode: undefined,
  categoryId: undefined,
  unitId: undefined,
  status: undefined,
  standard: undefined,
  remark: undefined,
  expiryDay: undefined,
  weight: undefined,
  purchasePrice: undefined,
  minPrice: undefined,
  imgUrl: [],
  priceList: [
    {
      id: undefined,
      price: undefined,
      startTime: undefined,
      endTime: undefined
    }
  ]
})
const formRules = reactive({
  name: [{ required: true, message: '样本名称不能为空', trigger: 'blur' }],
  barCode: [{ required: true, message: '样本条码不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '样本分类编号不能为空', trigger: 'blur' }],
  unitId: [{ required: true, message: '单位编号不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '样本状态不能为空', trigger: 'blur' }],
  priceList: [
    {
      type: 'array',
      required: true,
      message: '至少需要一条价格信息',
      trigger: 'change'
    },
    {
      validator: (rule: any, value: any[], callback: any) => {
        // 校验数组中的每一项
        const errors: string[] = []
        value.forEach((item, index) => {
          if (!item.price) {
            errors.push(`第${index + 1}行：价格不能为空`)
          }
          if (item.price < 0) {
            errors.push(`第${index + 1}行：价格不能小于0`)
          }
          if (item.price !== undefined && item.price !== null) {
            const priceStr = item.price.toString()
            const decimalIndex = priceStr.indexOf('.')
            if (decimalIndex !== -1 && priceStr.length - decimalIndex - 1 > 2) {
              errors.push(`第${index + 1}行：价格最多只能有两位小数`)
            }
          }
          if (!item.startTime) {
            errors.push(`第${index + 1}行：开始日期不能为空`)
          }
          if (!item.endTime) {
            errors.push(`第${index + 1}行：结束日期不能为空`)
          }
          if (item.startTime && item.endTime) {
            const start = new Date(item.startTime)
            const end = new Date(item.endTime)
            if (start > end) {
              errors.push(`第${index + 1}行：开始日期不得在结束日期之后`)
            }
          }
        })
        if (errors.length > 0) {
          callback(new Error(errors.join('；')))
          callback(message.error(errors.join('；')))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})
const formRef = ref() // 表单 Ref
const categoryList = ref<ProductCategoryVO[]>([]) // 样本分类列表
const unitList = ref<ProductUnitVO[]>([]) // 样本单位列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const product = await ProductApi.getProduct(id)
      // 1. 基础数据赋值（含imgUrl处理）
      formData.value = {
        ...product,
        imgUrl: product.imgUrl ? product.imgUrl.split(';') : [] // 处理图片 URL
      }
      // 2. 新增：时间戳转日期（适配el-date-picker）
      if (formData.value.priceList && formData.value.priceList.length > 0) {
        formData.value.priceList = formData.value.priceList.map((item) => ({
          ...item,
          // 时间戳（毫秒）转Date对象，若后端返回10位秒级时间戳，需先 *1000
          startTime: item.startTime ? new Date(item.startTime) : undefined,
          endTime: item.endTime ? new Date(item.endTime) : undefined
        }))
      }
      // 3. 原有逻辑：若没有明细数据，初始化一条
      if (!formData.value.priceList || formData.value.priceList.length === 0) {
        formData.value.priceList = [createEmptyDetail()]
      }
    } finally {
      formLoading.value = false
    }
  }
  // 样本分类
  const categoryData = await ProductCategoryApi.getProductCategorySimpleList()
  categoryList.value = handleTree(categoryData, 'id', 'parentId')
  // 样本单位
  unitList.value = await ProductUnitApi.getProductUnitSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProductVO
    data.imgUrl = (data.imgUrl || ([] as any)).join(';') // 处理图片 URL
    if (data.categoryId) {
      const categoryNodes = findPath(categoryList.value, (elem) => elem.id == data.categoryId)
      if (categoryNodes.length == 1) {
        data.parentCategoryId = categoryNodes[0].id // 设置父分类 ID
        data.categoryId = undefined
      } else if (categoryNodes.length > 1) {
        data.parentCategoryId = categoryNodes[0].id // 设置父分类 ID
      }
    }
    data.priceList = data.priceList.map((item) => {
      return {
        ...item,
        // startTime 转时间戳：先判断是否有效，再用 getTime() 取13位毫秒级时间戳
        startTime: item.startTime ? new Date(item.startTime).getTime() : undefined,
        // endTime 转时间戳：逻辑同上
        endTime: item.endTime ? new Date(item.endTime).getTime() : undefined
      }
    })
    if (formType.value === 'create') {
      await ProductApi.createProduct(data)
      message.success(t('common.createSuccess'))
    } else {
      data.productPriceList = data.priceList
      await ProductApi.updateProduct(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    barCode: undefined,
    categoryId: undefined,
    unitId: undefined,
    status: CommonStatusEnum.ENABLE,
    standard: undefined,
    remark: undefined,
    expiryDay: undefined,
    weight: undefined,
    purchasePrice: undefined,
    minPrice: undefined,
    imgUrl: [],
    priceList: [
      {
        id: undefined,
        price: undefined,
        startTime: undefined,
        endTime: undefined
      }
    ]
  }
  formRef.value?.resetFields()
}

/** 创建空的明细行 */
const createEmptyDetail = () => {
  return {
    id: undefined,
    price: undefined,
    startTime: undefined,
    endTime: undefined
  }
}
/** 添加一行 */
const addPriceList = () => {
  formData.value.priceList.push(createEmptyDetail())
}

/** 删除一行 */
const handleDelete = (index: number) => {
  // 至少保留一行
  if (formData.value.priceList.length <= 1) {
    message.warning('至少保留一条付款计划')
    return
  }
  formData.value.priceList.splice(index, 1)
}
</script>
